package com.vast.ui.component.socketinterface.server;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.net.Socket;

import com.vast.ui.component.socketinterface.request.Request;
import com.vast.ui.component.socketinterface.request.RequestQueue;
import com.vast.ui.component.state.Sequence;
import com.vast.ui.component.util.ConsoleLoggerSingleton;
import com.vast.ui.component.util.Logger;
import com.vast.ui.panel.led.Activator;

public class SendHandler  implements Runnable {
    private Socket              clientSendSocket;
    private DataOutputStream	out;
	private final Sequence      sequence;
	private final RequestQueue  sendQueue;
	private final Logger        logger;
	
	SendHandler(Socket clientSendSocket, Sequence sequence, RequestQueue sendQueue) {
        this.clientSendSocket = clientSendSocket;
        this.sequence      = sequence;
        this.sendQueue     = sendQueue;
        this.logger        = ConsoleLoggerSingleton.getInstance();
    }
    
    public void run() {
        try {
        	out = new DataOutputStream(new BufferedOutputStream(clientSendSocket.getOutputStream()));
        	
            while(sequence.isSendConnection()) {
            	Request request = sendQueue.getRequest();
            	int sizeOfData = 4 + request.data.length;
            	out.writeShort(sizeOfData);
            	out.writeShort(request.command);
            	out.write(request.data, 4, request.data.length - 4);
            	out.flush();
            	Thread.sleep(5);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
            	out.flush();
            	clientSendSocket.close();
            	logger.writeEntry(Activator.PLUGIN_ID + ": Exit Send Handler.");
            } catch (Exception e) {}
        }
    }
}
